<template>
  <ContentWrap>
    <el-button @click="backFirst">返 回</el-button>
  </ContentWrap>

  <el-form
    class="box"
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="100px"
    v-loading="formLoading"
  >
    <el-divider content-position="left"><span class="font-size-16px">课程信息</span></el-divider>
    <el-form-item label="教练" prop="coachId">
      <el-row type="flex" class="row-bg">
        <p v-if="formData.coachName">{{formData.coachName}}</p>
        <p v-else style="color: red">未分配</p>
        <el-button v-if="formData.status === 0" class="ml-10px" type="warning" @click="bindCoachIdShow">分配教练</el-button>
      </el-row>
    </el-form-item>
    <el-form-item label="用户昵称" prop="nickname">
      <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
    </el-form-item>
    <el-form-item label="联络手机号" prop="mobile">
      <el-input v-model="formData.mobile" placeholder="请输入联络手机号" />
    </el-form-item>
    <el-form-item label="上课日期" prop="attendClassDate">
      <el-date-picker
        v-model="formData.attendClassDate"
        type="date"
        value-format="YYYY-MM-DD"
        placeholder="选择上课日期"
      />
    </el-form-item>
    <el-form-item label="开始时间" prop="startTime">
      <el-time-picker
        v-model="formData.startTime"
        value-format="HH:mm"
        placeholder="选择开始时间"/>
    </el-form-item>
    <el-form-item label="教学分类" prop="serviceIds">
      <el-cascader
        class="w-100%"
        v-model="formData.serviceIds"
        :options="serviceClassTree"
        :props="{ label: 'name', value: 'id' }"
        filterable/>
    </el-form-item>
    <el-form-item label="授权场地" prop="venueId">
      <el-select v-model="formData.venueId" placeholder="请选择授权场地">
        <el-option
          v-for="item in venues"
          :key="item.id"
          :label="item.name"
          :value="item.id"/>
      </el-select>
    </el-form-item>
    <el-form-item label="教学人数" prop="peopleCount">
      <el-select v-model="formData.peopleCount" placeholder="请选择教学人数">
        <el-option
          v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_COACH_SERVICE_PEOPLE_COUNT)"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="教学时长" prop="serviceTime">
      <el-select v-model="formData.serviceTime" placeholder="请选择教学时间">
        <el-option
          v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_COACH_SERVICE_TIME)"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="雪板类型" prop="snowboardType">
      <el-select v-model="formData.snowboardType" placeholder="请选择雪板类型">
        <el-option
          v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_SNOWBOARD_TYPE)"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="滑行水平" prop="businessGlidingLevel">
      <el-select v-model="formData.businessGlidingLevel" placeholder="请选择滑行水平">
        <el-option
          v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_GLIDING_LEVEL)"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
    </el-form-item>

    <el-row v-if="formData.status != 4 && formData.status != 1" type="flex" class="row-bg" justify="space-around">
      <el-button @click="submitForm" type="primary" :disabled="formLoading">保存课程信息</el-button>
    </el-row>

    <el-divider content-position="left"><span class="font-size-16px">订单信息</span></el-divider>
    <el-form-item label="订单编号" prop="orderNo">
      {{formData.orderNo}}
    </el-form-item>
    <el-form-item label="订单状态" prop="status">
      <el-tag type="warning" v-if="formData.status === 0">待接单</el-tag>
      <el-tag type="info" v-else-if="formData.status === 1">已取消</el-tag>
      <el-tag type="danger" v-else-if="formData.status === 2">待上课</el-tag>
      <el-tag v-else-if="formData.status === 3">待确认</el-tag>
      <el-tag type="success" v-else>已完成</el-tag>
    </el-form-item>
    <el-form-item label="下单时间" prop="orderTime">
      {{formData.orderTime}}
    </el-form-item>
    <el-form-item label="接单时间" prop="receivedTime">
      {{formData.receivedTime || '-'}}
    </el-form-item>
    <el-form-item v-if="formData.status === 1" label="取消类型" prop="cancelType">
      <el-tag v-if="formData.cancelType === 1">系统取消</el-tag>
      <el-tag v-else-if="formData.cancelType === 2">用户取消</el-tag>
      <el-tag v-else-if="formData.cancelType === 3">教练取消</el-tag>
      <el-tag type="info" v-else>未取消</el-tag>
    </el-form-item>
    <el-form-item v-if="formData.status === 1 && formData.cancelType != 0" label="取消时间" prop="cancelTime">
      {{formData.cancelTime}}
    </el-form-item>
    <el-divider content-position="left"><span class="font-size-16px">支付信息</span></el-divider>
    <el-form-item label="支付状态" prop="paymentStatus">
      <el-tag type="success" v-if="formData.paymentStatus">已支付</el-tag>
      <el-tag type="info" v-else>未支付</el-tag>
    </el-form-item>
    <el-form-item label="订单金额" prop="paymentAmount">
      <p>￥ {{formData.paymentAmount / 100}} 元</p>
      <el-button v-if="!formData.paymentStatus" @click="updatePaymentAmount" class="ml-10px" type="primary">修改订单金额</el-button>
    </el-form-item>
    <el-form-item v-if="formData.paymentStatus" label="支付时间" prop="paymentTime">
      {{formData.paymentTime || '-'}}
    </el-form-item>
    <div v-if="formData.status > 2">
      <el-divider content-position="left"><span class="font-size-16px">教练上课信息</span></el-divider>
      <el-form-item label="上课时间" prop="attendClassTime">
        {{formData.attendClassTime || '-'}}
      </el-form-item>
      <el-form-item v-if="formData.attendClassTime" label="上课图片" prop="attendClassImages">
        <UploadImgs disabled v-model="formData.attendClassImages" />
      </el-form-item>
    </div>
    <div v-if="formData.status === 4">
      <el-divider content-position="left"><span class="font-size-16px">教练收益信息</span></el-divider>
      <el-form-item label="预估收益" prop="profitAmount">
        <p v-if="formData.profitAmount">{{formData.profitAmount / 100}}</p>
        <p v-else>-</p>
      </el-form-item>
      <el-form-item label="预计到账时间" prop="profitArrivalTime">
        {{formData.predictProfitArrivalTime || '-'}}
      </el-form-item>
      <el-form-item label="实际到账时间" prop="profitArrivalTime">
        {{formData.profitArrivalTime || '-'}}
      </el-form-item>
    </div>
    <div v-if="formData.status != 0">
      <el-divider content-position="left"><span class="font-size-16px">退款信息</span></el-divider>
      <el-form-item label="退款状态" prop="refundStatus">
        <el-tag type="info" v-if="formData.status === 0">未退款</el-tag>
        <el-tag type="danger" v-else-if="formData.status === 1">退款中</el-tag>
        <el-tag type="success" v-else>已到账</el-tag>
      </el-form-item>
      <el-form-item label="退款金额" prop="refundAmount">
        ￥ {{formData.refundAmount / 100}} 元
      </el-form-item>
      <el-form-item label="退款单号" prop="refundOrderNo">
        {{formData.refundOrderNo || '-'}}
      </el-form-item>
      <el-form-item label="退款时间" prop="refundTime">
        {{formData.refundTime || '-'}}
      </el-form-item>
      <el-form-item label="退款到账时间" prop="refundArrivalTime">
        {{formData.refundArrivalTime || '-'}}
      </el-form-item>
      <el-form-item v-if="formData.cancelType === 3" label="是否有违约金" prop="isDeductLiquidatedDamages">
        <p v-if="formData.isDeductLiquidatedDamages">有</p>
        <p v-else>无</p>
      </el-form-item>
      <el-form-item v-if="formData.cancelType === 3 && formData.isDeductLiquidatedDamages" label="教练违约金" prop="liquidatedDamages">
        <p v-if="formData.liquidatedDamages">￥ {{formData.liquidatedDamages / 100}}</p>
        <p v-else>-</p>
      </el-form-item>
    </div>
    <el-row type="flex" class="row-bg" justify="center">
      <el-button @click="backFirst">返 回</el-button>
      <el-button v-if="formData.status === 2" @click="attendClass" type="warning">上 课</el-button>
      <el-button v-if="formData.status != 4 && formData.status != 1" @click="cancelOrder" type="danger">取消订单</el-button>
    </el-row>
  </el-form>

  <Dialog title="修改订单金额" v-model="paymentAmountDialogVisible">
    <el-form-item label="订单金额" prop="coachId">
      <el-input-number style="width: 100%;" :min="0.01" v-model="newPaymentAmount" placeholder="请填写订单金额"/>
    </el-form-item>
    <template #footer>
      <el-button @click="submitUpdatePaymentAmount" type="primary">确 定</el-button>
      <el-button @click="paymentAmountDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <Dialog title="教练分配" v-model="selectCoachDialogVisible">
    <el-form-item label="教练" prop="coachId">
      <el-select v-model="selectCoachInfo.id" placeholder="请选择教练">
        <el-option
          v-for="item in coachList"
          :key="item.id"
          :label="item.nickname"
          :value="item.id"/>
      </el-select>
    </el-form-item>
    <template #footer>
      <el-button @click="bindCoachId" type="primary">确 定</el-button>
      <el-button @click="selectCoachDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <Dialog title="订单上课" v-model="attendClassDialogVisible">
    <el-form-item label="上课时间" prop="attendClassTime">
      <el-date-picker
        v-model="attendClassInfo.attendClassTime"
        type="datetime"
        value-format="YYYY-MM-DD HH:mm:ss"
        placeholder="选择上课时间"
      />
    </el-form-item>
    <el-form-item label="上课图片" prop="attendClassImages">
      <UploadImgs :limit="24" :file-size="24" v-model="attendClassInfo.attendClassImages" />
    </el-form-item>
    <template #footer>
      <el-button @click="submitAttendClass" type="primary">确 定</el-button>
      <el-button @click="attendClassDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { OrderApi, Order } from '@/api/business/order'
import {handleTree} from "@/utils/tree";
import {useTagsView} from "@/hooks/web/useTagsView";
import {VenueApi} from "@/api/business/venue";
import {ServiceClassApi} from "@/api/business/serviceclass";
import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";
import {CoachApi} from "@/api/business/coach";
const { closeCurrent } = useTagsView()

let normal = ref('info')

const backFirst = async () => {
  router.push({
    name: 'BizOrder'
  })
  closeCurrent(this)
}

/** 订单 表单 */
defineOptions({ name: 'OrderDetail' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  userId: undefined,
  orderNo: undefined,
  coachId: undefined,
  coachName: undefined,
  attendClassDate: undefined,
  venueId: undefined,
  serviceIds: undefined,
  startTime: undefined,
  peopleCount: undefined,
  serviceTime: undefined,
  snowboardType: undefined,
  businessGlidingLevel: undefined,
  nickname: undefined,
  mobile: undefined,
  remark: undefined,
  estimatedAmount: undefined,
  paymentAmount: undefined,
  profitAmount: undefined,
  profitArrivalTime: undefined,
  orderTime: undefined,
  paymentStatus: undefined,
  paymentTime: undefined,
  receivedTime: undefined,
  cancelTime: undefined,
  cancelType: undefined,
  attendClassTime: undefined,
  attendClassImages: undefined,
  orderType: undefined,
  status: undefined,
  refundStatus: undefined,
  refundOrderNo: undefined,
  refundTime: undefined,
  refundArrivalTime: undefined,
  predictProfitArrivalTime: undefined,
  refundAmount: undefined,
  isDeductLiquidatedDamages: undefined,
  liquidatedDamages: undefined,
})
const formRules = reactive({
  attendClassDate: [{ required: true, message: '上课日期不能为空', trigger: 'blur' }],
  venueId: [{ required: true, message: '上课地点不能为空', trigger: 'blur' }],
  serviceIds: [{ required: true, message: '教学分类不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  peopleCount: [{ required: true, message: '教学人数不能为空', trigger: 'blur' }],
  serviceTime: [{ required: true, message: '教学时间不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  mobile: [{ required: true, message: '联络手机号不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const initDetail = async () => {
  resetForm()
  formLoading.value = true
  try {
    formData.value = await OrderApi.getOrder(orderId.value)
  } finally {
    formLoading.value = false
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Order
    await OrderApi.updateOrder(data)
    await initDetail()
    message.success(t('common.updateSuccess'))
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    orderNo: undefined,
    coachId: undefined,
    coachName: undefined,
    attendClassDate: undefined,
    venueId: undefined,
    serviceIds: undefined,
    startTime: undefined,
    peopleCount: undefined,
    serviceTime: undefined,
    snowboardType: undefined,
    businessGlidingLevel: undefined,
    nickname: undefined,
    mobile: undefined,
    remark: undefined,
    estimatedAmount: undefined,
    paymentAmount: undefined,
    profitAmount: undefined,
    profitArrivalTime: undefined,
    orderTime: undefined,
    paymentStatus: undefined,
    paymentTime: undefined,
    receivedTime: undefined,
    cancelTime: undefined,
    cancelType: undefined,
    attendClassTime: undefined,
    attendClassImages: undefined,
    orderType: undefined,
    status: undefined,
    refundStatus: undefined,
    refundOrderNo: undefined,
    refundTime: undefined,
    refundArrivalTime: undefined,
    predictProfitArrivalTime: undefined,
    refundAmount: undefined,
    isDeductLiquidatedDamages: undefined,
    liquidatedDamages: undefined,
  }
  formRef.value?.resetFields()
}

// 取消订单
const cancelOrder = async () => {
  await message.confirm("确认取消订单吗？", "取消订单")

  try {
    await OrderApi.orderCancel(orderId.value)
    message.success('取消成功')
  }finally {
    await initDetail()
  }
}

// 上课
const attendClassDialogVisible = ref(false)
let attendClassInfo = ref({
  attendClassTime: undefined,
  attendClassImages: []
})
const attendClass = async () => {
  attendClassInfo.value = {attendClassTime: undefined, attendClassImages: []}
  attendClassDialogVisible.value = true
}
const submitAttendClass = async () => {
  await OrderApi.updateOrderAttendClass({
    id: orderId.value,
    attendClassTime: attendClassInfo.value.attendClassTime,
    attendClassImages: attendClassInfo.value.attendClassImages
  })
  message.success('上课成功')
  formData.value.attendClassTime = attendClassInfo.value.attendClassTime
  formData.value.attendClassImages = attendClassInfo.value.attendClassImages
  attendClassDialogVisible.value = false
}


// 更新订单金额
const paymentAmountDialogVisible = ref(false)
let newPaymentAmount = ref()
const updatePaymentAmount = async () => {
  newPaymentAmount.value = undefined
  paymentAmountDialogVisible.value = true
  newPaymentAmount.value = formData.value.paymentAmount / 100
}
const submitUpdatePaymentAmount = async () => {
  const finalAmount = newPaymentAmount.value * 100;
  await OrderApi.updateOrderAmount({id: orderId.value, paymentAmount: finalAmount})
  message.success('金额修改成功')
  formData.value.paymentAmount = finalAmount
  paymentAmountDialogVisible.value = false
}


// 绑定教练
const selectCoachDialogVisible = ref(false)
let selectCoachInfo = ref({
  id: undefined,
  nickname: undefined,
})
const bindCoachIdShow = async () => {
  selectCoachInfo.value = {id: undefined, nickname: undefined}

  selectCoachDialogVisible.value = true
  if (formData.value.coachId) {
    selectCoachInfo.value.id = formData.value.coachId
    selectCoachInfo.value.nickname = formData.value.coachName
  }
}
const bindCoachId = async () => {
  if (selectCoachInfo.value.id){
    formData.value.coachId = selectCoachInfo.value.id;
    formData.value.coachName = coachList.value.find(item => item.id == selectCoachInfo.value.id)?.nickname;
  }

  selectCoachDialogVisible.value = false;
}


const coachList = ref([])
const getCoachAll = async () => {
  coachList.value = await CoachApi.getCoachAll()
}

const venues = ref([])
const getVenueAll = async () => {
  venues.value = await VenueApi.getVenueAll()
}

const serviceClassTree = ref([])
const getServiceClassAll = async () => {
  serviceClassTree.value = []
  const data = await ServiceClassApi.getServiceClassAll()
  serviceClassTree.value = handleTree(data, 'id', 'parentId')
}

const route = useRoute() // 路由
const router = useRouter() // 路由

let orderId = ref()

/** 初始化 **/
onMounted(() => {
  // 如果数据 ID 不存在，显示错误提示并关闭页面
  if (!route.query.id) {
    message.error('订单 ID 不存在，无法查看详情')
    // 关闭当前路由，返回到数据列表页面
    router.push({ name: 'BizOrder' })
    return
  }

  orderId.value = route.query.id;
  initDetail()
  getVenueAll()
  getCoachAll()
  getServiceClassAll()
})
</script>

<style scoped>
.box{
  width: 100%;
  background: white;
  padding: 10px;
}
</style>
